import md5 from 'js-md5'
import React, { Component } from 'react'
import { SafeAreaView, StyleSheet } from 'react-native'
import { px2dp, showToast } from 'rn-xiaobu-utils'
import ajaxAsync from '../../../src/utils/ajaxAsync'
import { getTitleBarOptions } from '../../../src/utils/DefaultTitleOption'

import LoginBtn from '../../components/login/loginbtn/LoginBtn'
import CodeInput from '../../components/login/logininput/CodeInput'
import PhoneInput from '../../components/login/logininput/PhoneInput'

export default class FirstPage extends Component {
  static navigationOptions = ({ navigation }) => {
    return getTitleBarOptions({ navigation }, { headerTitle: '验证码登录' })
  }

  componentWillUnmount () {
    this.refs.codeInput._resetCount()
  }

  // 自定义的函数都使用定义属性的写法，否则会取不到this
  _onLoginButton = () => {
    // 验证码登录
    Promise.all([
      this.refs.phoneInput._validText(),
      this.refs.codeInput._validText()
    ]).then(result => {
      let sendObj = {
        USERNAME: result[0],
        PASSWORD_MD5: md5(result[1])
      }
      ajaxAsync('/user/login', sendObj).then(() => {
        showToast('登录成功')
        this.props.navigation.dismiss()
      })
    }).catch(err => {
      showToast(err.message)
    })
  }

  _getCode = () => {
    this.refs.phoneInput._validText().then(phone => {
      let sendObj = {
        PHONE: phone
      }
      ajaxAsync('user/smscode/get', sendObj).then(() => {
        showToast('验证码发送成功')
        this.refs.codeInput._countDown()
      })
    }).catch(err => {
      showToast(err.message)
    })
  }

  render () {
    return (
      <SafeAreaView style={styles.container}>
        <PhoneInput ref="phoneInput"/>
        <CodeInput ref="codeInput" getCode={this._getCode}/>
        <LoginBtn text="登录" onPress={this._onLoginButton}/>
      </SafeAreaView>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    alignItems: 'center',
    backgroundColor: '#ffffff',
    paddingLeft: px2dp(30),
    paddingRight: px2dp(30),
    position: 'relative'
  }
})
